﻿function AzureOnlineMetaEditor() {

    var self = this;

    var rows = ko.observableArray([]);

    var nameRegex = new RegExp('^[a-zA-Z_][a-zA-Z0-9_]*$');

    function createRow() {

        var name = ko.observable('');

        var value = ko.observable('');

        var empty = ko.computed(function () {
            return utils.isNullOrWhiteSpace(name()) && utils.isNullOrWhiteSpace(value());
        });

        var nameValid = ko.computed(function () {
            var str = name();
            if (utils.isNullOrWhiteSpace(str)) return true;
            str = str.trim();
            if (nameRegex.test(str)) {
                return true;
            }
            return false;
        });

        var valid = ko.computed(function () {
            return nameValid();
        });
        
        return {
            name: name,
            value: value,
            empty: empty,
            valid: valid,
            nameValid: nameValid
        };
    }

    ko.computed(function () {
        var list = rows();
        var needCount = 0;
        for (var i = list.length - 1; i >= 0; i--) {
            var item = list[i];
            if (!item.empty()) {
                needCount = i + 1;
                break;
            }
        }
        needCount += 1;
        while (list.length > needCount) {
            rows.remove(list[list.length - 1]);
        }
        while (list.length < needCount) {
            var row = createRow();
            row.name();
            row.value();
            rows.push(row);
        }
    });

    function init(meta) {
        var res = [];
        for (var i = 0; i < meta.length; i++) {
            var item = meta[i];
            var row = createRow();
            row.name(item.name);
            row.value(item.value);
            res.push(row);
        }
        rows(res);
    }

    function validate() {
        var rs = rows();
        for (var i = 0; i < rs.length; i++) {
            var row = rs[i];
            if (!row.valid()) return false;
        }
        return true;
    }

    function getInfo() {
        var res = [];
        var list = rows();
        for (var i = 0; i < list.length; i++) {
            var row = list[i];
            if (!row.empty()) {
                var info = {
                    name: row.name(),
                    value: row.value()
                };
                res.push(info);
            }
        }
        return res;
    }

    self.rows = rows;
    self.init = init;
    self.validate = validate;
    self.getInfo = getInfo;
}